package main

import (
	"github.com/dgrijalva/jwt-go"
	"log"
	"math/rand"
	"time"
)

// 参考: https://www.jianshu.com/p/6d1885f218c8
//sub: 该JWT所面向的用户
//iss: 该JWT的签发者
//iat(issued at): 在什么时候签发的token
//exp(expires): token什么时候过期
//nbf(not before)：token在此时间之前不能被接收处理
//jti：JWT ID为web token提供唯一标识
func main() {

	key := "FUXhPEwRmiWslf7rZpu8CACJ02CgfJXBjsy4FstW33qwjA8ywooC6HPSqqpIP2wZ"
	token := jwt.New(jwt.SigningMethodHS256)
	claims := make(jwt.MapClaims)
	claims["iss"] = "http://127.0.0.1:8000/v2/login"
	claims["iat"] = time.Now().Unix()
	claims["exp"] = time.Now().Add(time.Second * time.Duration(1)).Unix()
	claims["nbf"] = time.Now().Unix()
	claims["jti"] = randomKey(16) /// "PtGsk10GW7eC19I1"
	claims["sub"] = 1
	claims["prv"] = "23bd5c8949f600adb39e701c400872db7a5976f7"
	token.Claims = claims
	tokenString, err := token.SignedString([]byte(key))
	if err != nil {
		panic(err)
	}
	log.Println(tokenString)
}

var _randomKey = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890"

func randomKey(length int) string {
	result := ""
	r := rand.New(rand.NewSource(time.Now().Unix()))
	rkl := len(_randomKey)
	for i := 0; i < length; i++ {
		randInt := r.Intn(rkl)
		result = result + _randomKey[randInt:randInt+1]
	}
	return result
}
